let startTime = null;
let remainingTimeEstimates = [];

// 更新未分类书签数量的函数
function updateUnclassifiedCount(count) {
    document.getElementById('unclassified-count').textContent = count;
}

// 查找AI分类文件夹
async function findAIFolder() {
    let bookmarks = await chrome.bookmarks.getTree();
    let queue = [...bookmarks];
    while (queue.length > 0) {
        let node = queue.shift();
        if (node.title === "AI分类") {
            return node;
        }
        if (node.children) {
            queue.push(...node.children);
        }
    }
    return null;
}

// 收集已存在的URL
async function collectExistingUrls(folder, urlSet) {
    if (folder.url) {
        urlSet.add(folder.url);
    }
    if (folder.children) {
        for (let child of folder.children) {
            await collectExistingUrls(child, urlSet);
        }
    }
}
// 在页面加载时初始化未分类书签数量
document.addEventListener('DOMContentLoaded', async () => {
    const loadingElement = document.getElementById('loading');
    const loadingTextElement = document.querySelector('.loading-text');
    const outputElement = document.getElementById('output');
    const classifyButton = document.getElementById('classify');
    const openSettingsButton = document.getElementById('open_settings');
    const saveBookmarksButton = document.getElementById('save_bookmarks');

    let bookmarks = await chrome.bookmarks.getTree();
    let unclassifiedCount = 0;

    // 获取AI分类文件夹中的所有书签URL
    let aiFolder = await findAIFolder();
    let existingUrls = new Set();
    if (aiFolder) {
        let aiBookmarks = await chrome.bookmarks.getSubTree(aiFolder.id);
        await collectExistingUrls(aiBookmarks[0], existingUrls);
    }

    // 用于去重的URL集合
    let seenUrls = new Set();
    function traverse(nodes) {
        for (let node of nodes) {
            if (node.url) {
                // 跳过已在AI分类文件夹中的书签
                if (existingUrls.has(node.url)) {
                    continue;
                }
                // 跳过重复的URL
                if (seenUrls.has(node.url)) {
                    continue;
                }
                seenUrls.add(node.url);
                unclassifiedCount++;
            }
            if (node.children) {
                traverse(node.children);
            }
        }
    }
    traverse(bookmarks);
    updateUnclassifiedCount(unclassifiedCount);

    // 隐藏加载提示
    loadingElement.style.display = 'none';

    // 注册事件监听器
    openSettingsButton.addEventListener('click', function() {
        chrome.runtime.openOptionsPage();
    });

    classifyButton.addEventListener('click', async () => {
        outputElement.innerHTML = '';
        loadingElement.style.display = 'flex';
        loadingTextElement.textContent = '正在准备分类数据...';

        let bookmarks = await chrome.bookmarks.getTree();
        let flatBookmarks = [];
        let unclassifiedCount = 0;

        // 获取AI分类文件夹中的所有书签URL
        let aiFolder = await findAIFolder();
        let existingUrls = new Set();
        if (aiFolder) {
            let aiBookmarks = await chrome.bookmarks.getSubTree(aiFolder.id);
            await collectExistingUrls(aiBookmarks[0], existingUrls);
        }

        // 用于去重的URL集合
        let seenUrls = new Set();
        function traverse(nodes) {
            for (let node of nodes) {
                if (node.url) {
                    // 跳过已在AI分类文件夹中的书签
                    if (existingUrls.has(node.url)) {
                        continue;
                    }
                    // 跳过重复的URL
                    if (seenUrls.has(node.url)) {
                        continue;
                    }
                    seenUrls.add(node.url);
                    flatBookmarks.push(node);
                    unclassifiedCount++;
                }
                if (node.children) {
                    traverse(node.children);
                }
            }
        }
        traverse(bookmarks);
        updateUnclassifiedCount(unclassifiedCount);

        chrome.storage.sync.get(['baseUrl', 'apiKey', 'model', 'classifyMode', 'reclassify'], async (data) => {
            let baseUrl = data.baseUrl || 'https://ark.cn-beijing.volces.com/api/v3';
            let apiKey = data.apiKey;
            let model = data.model || 'gpt-4';
            let classifyMode = data.classifyMode || 'one_by_one'; // 默认使用逐个分类
            let reclassify = data.reclassify === 'true'; // 转换为布尔值

            if (!apiKey) {
                alert('请在设置页面中配置 API Key');
                chrome.runtime.openOptionsPage();
                return;
            }

            // 根据reclassify设置决定是否重新处理已分类的书签
            if (reclassify) {
                flatBookmarks = [];
                function traverseAll(nodes) {
                    for (let node of nodes) {
                        if (node.url && !seenUrls.has(node.url)) {
                            seenUrls.add(node.url);
                            flatBookmarks.push(node);
                        }
                        if (node.children) {
                            traverseAll(node.children);
                        }
                    }
                }
                traverseAll(bookmarks);
                updateUnclassifiedCount(flatBookmarks.length);
            }

            let categories;
            if (classifyMode === 'one_by_one') {
                categories = await classifyBookmarksOneByOne(flatBookmarks, baseUrl, apiKey, model);
            } else if (classifyMode === 'batch') {
                categories = await classifyBookmarksInBatches(flatBookmarks, baseUrl, apiKey, model, 20);
            } else {
                // 如果classifyMode不是有效值，默认使用逐个分类
                categories = await classifyBookmarksOneByOne(flatBookmarks, baseUrl, apiKey, model);
            }
            renderCategories(categories);
            saveBookmarksButton.style.display = 'block';
        });
    });

    saveBookmarksButton.addEventListener('click', () => {
        let categories = outputElement.dataset.categories ? JSON.parse(outputElement.dataset.categories) : {};

        if (Object.keys(categories).length === 0) {
            alert('没有可保存的书签分类！');
            return;
        }
        
        chrome.storage.sync.get(['saveFolder'], (data) => {
            const folderName = data.saveFolder || 'AI分类';
            // 创建根文件夹
            chrome.bookmarks.create({ title: folderName }, (rootFolder) => {
                if (chrome.runtime.lastError) {
                    console.error('创建AI分类文件夹失败:', chrome.runtime.lastError);
                    alert('创建AI分类文件夹失败');
                    return;
                }

                let totalBookmarks = 0;
                let savedBookmarks = 0;
                Object.values(categories).forEach(bookmarks => {
                    totalBookmarks += bookmarks.length;
                });

                // 在 AI分类 文件夹下创建各个分类子文件夹
                Object.keys(categories).forEach(category => {
                    chrome.bookmarks.create({ 
                        parentId: rootFolder.id,
                        title: category 
                    }, (folder) => {
                        if (chrome.runtime.lastError) {
                            console.error('创建分类文件夹失败:', chrome.runtime.lastError);
                            alert(`创建分类文件夹 "${category}" 失败`);
                            return;
                        }

                        categories[category].forEach(bookmark => {
                            chrome.bookmarks.create({
                                parentId: folder.id,
                                title: bookmark.title,
                                url: bookmark.url
                            }, (createdBookmark) => {
                                if (chrome.runtime.lastError) {
                                    console.error('创建书签失败:', chrome.runtime.lastError);
                                    alert(`保存书签 "${bookmark.title}" 失败`);
                                } else {
                                    savedBookmarks++;
                                    if (savedBookmarks === totalBookmarks) {
                                        alert(`保存完成！成功创建 ${Object.keys(categories).length} 个分类文件夹，保存 ${savedBookmarks} 个书签。`);
                                    }
                                }
                            });
                        });
                    });
                });
            });
        });
    });
});




async function classifySingleBookmark(baseUrl, apiKey, model, bookmark) {
    try {
        let response = await fetch(`${baseUrl}/chat/completions`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Authorization": `Bearer ${apiKey}`
            },
            body: JSON.stringify({
                model: model,
                messages: [
                    {
                        role: "system",
                        content: `你是一个浏览器收藏夹分类助手，请根据书签标题和URL返回最合适的分类名称（如：新闻、影音、购物等），只需返回分类名称，不要其他内容。`
                    },
                    {
                        role: "user",
                        content: `分类这个书签：标题“${bookmark.title}”，URL“${bookmark.url}”`
                    }
                ],
                stream: false,
                response_format: { type: "text" }
            })
        });

        let data = await response.json();
        let category = data.choices[0].message.content.trim().replace(/^["']|["']$/g, '');
        let tokens = data.usage?.total_tokens || 0;
        return { category, tokens };
    } catch (error) {
        console.error("分类请求失败:", error);
        return { category: "未分类", tokens: 0 };
    }
}


function updateProgress(current, total, total_time = 0, tokens = 0) {
    // 进度条更新
    const progressPercent = (current / total * 100).toFixed(1);
    document.querySelector('.progress-bar').style.width = `${progressPercent}%`;

    // 动态颜色变化
    const hue = 210 + (progressPercent * 1.5);
    document.querySelector('.progress-bar').style.background =
        `linear-gradient(90deg, hsl(${hue}, 100%, 50%) 0%, hsl(${hue + 20}, 100%, 60%) 100%)`;

    // 详细数据更新
    document.getElementById('processed-count').textContent = `${current}/${total}`;

    document.getElementById('live-tokens').textContent = tokens;

    // 格式化总耗时
    let timeDisplay;
    if (total_time < 60) {
        timeDisplay = total_time.toFixed(3) + 's';
    } else {
        const totalMins = Math.floor(total_time / 60);
        const totalSecs = (total_time % 60).toFixed(3);
        timeDisplay = `${totalMins}m ${totalSecs}s`;
    }
    document.getElementById('total_time').textContent = timeDisplay;
    console.log(`${current}/${total}，总耗时：${timeDisplay}`);

    // 剩余时间估算（增强版）
    if (!startTime) startTime = Date.now();
    const elapsed = (Date.now() - startTime) / 1000; // 秒
    const itemsPerSecond = current / elapsed;
    const remainingTime = (total - current) / itemsPerSecond;


    // 使用加权平均算法
    remainingTimeEstimates.push(remainingTime);
    if (remainingTimeEstimates.length > 5) remainingTimeEstimates.shift();

    const weightedEstimates = remainingTimeEstimates.map((t, i) =>
        t * (remainingTimeEstimates.length - i)
    );
    const avgRemaining = weightedEstimates.reduce((a, b) => a + b, 0)
        / weightedEstimates.length;

    // 格式化为分钟:秒
    const mins = Math.floor(avgRemaining / 60);
    const secs = Math.floor(avgRemaining % 60);
    document.getElementById('eta').textContent =
        `${mins}m ${secs.toString().padStart(2, '0')}s`;

    // 自动滚动保持可见
    const progressContainer = document.querySelector('.progress-container');
    progressContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });

}


async function classifyBookmarksOneByOne(bookmarks, baseUrl, apiKey, model) {
    // 初始化进度显示
    const progressContainer = document.querySelector('.progress-container');
    const detailedProgress = document.getElementById('detailed-progress');
    progressContainer.style.display = 'block';
    detailedProgress.style.display = 'grid';
    progressContainer.classList.add('active');
    detailedProgress.classList.add('active');
    startTime = Date.now();
    remainingTimeEstimates = [];
    let categories = {};
    let totalTokens = 0;
    let processed = 0;
    const total = bookmarks.length;

    document.getElementById("loading").style.display = 'none';
    for (const bookmark of bookmarks) {
        processed++;

        let { category, tokens } = await classifySingleBookmark(baseUrl, apiKey, model, bookmark);
        totalTokens += tokens;

        if (!categories[category]) categories[category] = [];
        categories[category].push(bookmark);

        const elapsed = (Date.now() - startTime) / 1000;
        updateProgress(processed, total, elapsed, totalTokens);
        updateCategoryUI(category, bookmark);
    }
    document.getElementById("loading").innerText = "";
    // 完成后隐藏进度条
    document.querySelector('.progress-container').style.display = 'none';
    // document.getElementById('detailed-progress').style.display = 'none';

    return categories;
}

async function classifyBookmarksInBatches(bookmarks, baseUrl, apiKey, model, batchSize) {
    // 初始化进度显示
    const progressContainer = document.querySelector('.progress-container');
    const detailedProgress = document.getElementById('detailed-progress');
    progressContainer.style.display = 'block';
    detailedProgress.style.display = 'grid';
    progressContainer.classList.add('active');
    detailedProgress.classList.add('active');
    startTime = Date.now();
    remainingTimeEstimates = [];
    let categories = {};
    let totalTokens = 0;
    let processed = 0;
    const total = bookmarks.length;

    document.getElementById("loading").style.display = 'none';
    // 将书签分成批次
    for (let i = 0; i < bookmarks.length; i += batchSize) {
        const batch = bookmarks.slice(i, i + batchSize);
        const batchPromises = batch.map(async (bookmark) => {
            let { category, tokens } = await classifySingleBookmark(baseUrl, apiKey, model, bookmark);
            return { bookmark, category, tokens };
        });

        // 等待当前批次的所有分类完成
        const results = await Promise.all(batchPromises);

        // 处理结果
        results.forEach(({ bookmark, category, tokens }) => {
            processed++;
            totalTokens += tokens;

            if (!categories[category]) categories[category] = [];
            categories[category].push(bookmark);

            const elapsed = (Date.now() - startTime) / 1000;
            updateProgress(processed, total, elapsed, totalTokens);
            updateCategoryUI(category, bookmark);
        });

        // 更新进度显示
        const elapsed = (Date.now() - startTime) / 1000;
        updateProgress(processed, total, elapsed, totalTokens);
        updateCategoryUI(category, bookmark);
    }

    document.getElementById("loading").innerText = "";
    document.querySelector('.progress-container').style.display = 'none';

    return categories;
}
function updateCategoryUI(categoryName, bookmark) {
    let output = document.getElementById("output");
    let existingCategory = Array.from(output.children).find(li =>
        li.querySelector('.folder').textContent.startsWith(categoryName)
    );

    if (existingCategory) {
        let span = existingCategory.querySelector('.folder');
        let ul = existingCategory.querySelector('ul');
        let count = ul.children.length + 1;
        span.textContent = `${categoryName} (${count})`;
        ul.appendChild(createBookmarkLi(bookmark));
    } else {
        let li = document.createElement("li");
        let span = document.createElement("span");
        span.className = "folder";
        span.textContent = `${categoryName} (1)`;
        
        let ul = document.createElement("ul");
        ul.className = "tree hidden";
        ul.appendChild(createBookmarkLi(bookmark));
        
        span.addEventListener('click', toggleCategory);
        
        li.appendChild(span);
        li.appendChild(ul);
        output.appendChild(li);
    }
}

function createBookmarkLi(bookmark) {
    let li = document.createElement("li");
    let a = document.createElement("a");
    a.href = bookmark.url;
    a.target = "_blank";
    a.textContent = bookmark.title;
    li.appendChild(a);
    return li;
}

function toggleCategory(e) {
    e.preventDefault();
    const ul = e.target.nextElementSibling;
    if (ul && ul.classList.contains('tree')) {
        ul.classList.toggle("hidden");
        e.target.classList.toggle("expanded");
        
        // 添加平滑过渡效果
        if (!ul.classList.contains("hidden")) {
            ul.style.maxHeight = ul.scrollHeight + "px";
        } else {
            ul.style.maxHeight = "0";
        }
    }
}

function renderCategories(categories) {
    let output = document.getElementById("output");
    output.innerHTML = "";
    output.dataset.categories = JSON.stringify(categories);

    Object.keys(categories).sort().forEach(category => {
        let li = document.createElement("li");
        let span = document.createElement("span");
        span.innerText = `${category} (${categories[category].length})`;
        span.className = "folder";
        
        let ul = document.createElement("ul");
        ul.className = "tree hidden";
        ul.style.maxHeight = "0";
        ul.style.overflow = "hidden";
        ul.style.transition = "max-height 0.3s ease-in-out";
        
        // 为每个分类文件夹添加点击事件
        span.addEventListener('click', toggleCategory);

        // 按标题字母顺序排序书签
        categories[category]
            .sort((a, b) => a.title.localeCompare(b.title))
            .forEach(bookmark => {
                let subLi = document.createElement("li");
                let a = document.createElement("a");
                a.href = bookmark.url;
                a.target = "_blank";
                a.innerText = bookmark.title;
                subLi.appendChild(a);
                ul.appendChild(subLi);
            });

        li.appendChild(span);
        li.appendChild(ul);
        output.appendChild(li);
    });
}
